<template>
  <div class="talk-publish-page">
    <n-card title="发布说说" class="publish-card">
      <n-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-placement="left"
        label-width="auto"
        require-mark-placement="right-hanging"
        size="medium"
      >
        <!-- 内容输入 -->
        <n-form-item label="内容" path="content">
          <n-input
            :value="formData.content"
            @update:value="formData.content = $event"
            type="textarea"
            placeholder="分享你的想法..."
            :autosize="{ minRows: 3, maxRows: 8 }"
            show-count
            maxlength="500"
          />
        </n-form-item>

        <!-- 媒体文件上传 -->
        <n-form-item label="媒体文件">
          <MediaUpload
            :model-value="fileList"
            @update:model-value="handleFileListUpdate"
            :max-files="9"
            accept="all"
            upload-text="记录即刻"
          />
        </n-form-item>

        <!-- 标签输入 -->
        <n-form-item label="标签">
          <n-select
            :value="formData.tags"
            @update:value="handleTagChange"
            :options="filteredTagOptions"
            multiple
            filterable
            placeholder="搜索或选择标签"
            :loading="tagLoading"
            :on-remove="removeTag"
            style="width: 100%"
            clearable
            :on-search="handleTagSearch"
          />
        </n-form-item>

        <!-- 位置信息 -->
        <n-form-item label="位置">
          <n-space vertical>
            <n-input
              :value="formData.address"
              @update:value="formData.address = $event"
              placeholder="添加位置信息（可选）"
              clearable
            />
            <n-button
              size="small"
              @click="loadLocationAndWeather"
              :loading="locationLoading"

              ghost
            >
              自动获取位置和天气
            </n-button>
          </n-space>
        </n-form-item>

        <!-- 天气信息 -->
        <n-form-item label="天气">
          <n-input
            :value="formData.weather"
            @update:value="formData.weather = $event"
            placeholder="添加天气信息（可选）"
            clearable
          />
        </n-form-item>

        <!-- 操作按钮 -->
        <n-form-item>
          <n-space>
            <n-button type="primary" @click="handleSubmit" :loading="submitting">
              {{ isEdit ? '更新' : '发布' }}
            </n-button>
            <n-button @click="handleCancel">取消</n-button>
            <n-button @click="handleReset">重置</n-button>
          </n-space>
        </n-form-item>
      </n-form>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import type { FormInst, UploadFileInfo } from 'naive-ui'
import MediaUpload from '@/components/common/MediaUpload.vue'
import { talkApi } from '@/api/talk'
import { tagApi } from '@/api/tag'
import { getLocationAndWeather } from '../api/location'
// 移除 uploadApi 导入，不再需要删除七牛云文件功能
import type { TalkItem } from '@/types/talk'

const route = useRoute()
const router = useRouter()
const message = useMessage()

// 表单引用
const formRef = ref<FormInst>()

// 是否为编辑模式
const isEdit = ref(false)
const talkId = ref<number | null>(null)

// 提交状态
const submitting = ref(false)

// 文件列表
const fileList = ref<UploadFileInfo[]>([])

// 表单数据
const formData = reactive({
  content: '',
  photos: [] as { url: string }[],
  tags: [] as string[],
  address: '',
  weather: ''
})

// 表单验证规则
const rules = {
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 1, max: 500, message: '内容长度在 1 到 500 个字符', trigger: 'blur' }
  ]
}

// 已上传的文件URL列表（用于删除）
const uploadedFiles = ref<string[]>([])

// 标签相关
interface TagOption {
  label: string
  value: string
  type?: 'create'
}

const tagOptions = ref<TagOption[]>([])
const filteredTagOptions = ref<TagOption[]>([])
const tagLoading = ref(false)
const searchKeyword = ref('')
const locationLoading = ref(false)

// 处理文件列表更新
const handleFileListUpdate = (newFileList: UploadFileInfo[]) => {
  console.log('handleFileListUpdate 被调用，新的文件列表:', newFileList)
  console.log('第一个文件对象:', newFileList[0])
  console.log('第一个文件的status:', newFileList[0]?.status)
  console.log('第一个文件的url:', newFileList[0]?.url)

  fileList.value = newFileList

  // 更新已上传的文件列表
  uploadedFiles.value = newFileList
    .filter(file => file.status === 'finished' && file.url)
    .map(file => file.url!)

  console.log('已上传的文件URL列表:', uploadedFiles.value)

  // 更新表单数据
  formData.photos = newFileList
    .filter(file => file.status === 'finished' && file.url)
    .map(file => ({ url: file.url! }))

  console.log('更新后的 formData.photos:', formData.photos)
  console.log('当前 formData:', formData)
}

// 初始化数据
onMounted(async () => {
  const editId = route.params.id
  if (editId) {
    isEdit.value = true
    talkId.value = Number(editId)
    await loadTalkData()
  } else {
    // 新建模式：自动获取位置和天气信息
    await loadLocationAndWeather()
  }
  await loadTags()
})

// 加载位置和天气信息
const loadLocationAndWeather = async () => {
  try {
    locationLoading.value = true
    console.log('正在获取位置和天气信息...')
    const { address, weather } = await getLocationAndWeather()

    // 设置初始值
    if (address && !formData.address) {
      formData.address = address
      console.log('设置地址:', address)
    }

    if (weather && !formData.weather) {
      formData.weather = weather
      console.log('设置天气:', weather)
    }

    message.success('位置和天气信息已更新')
  } catch (error) {
    console.warn('获取位置和天气信息失败，使用默认值:', error)
    message.warning('获取位置和天气信息失败，请手动输入')
    // 获取失败时不影响其他功能
  } finally {
    locationLoading.value = false
  }
}

// 加载说说数据（编辑模式）
const loadTalkData = async () => {
  try {
    if (!talkId.value) return

    const response = await talkApi.getTalkDetail(talkId.value)
    console.log('加载说说数据:', response)

    // 填充表单数据
    formData.content = response.content || ''
    formData.tags = response.tags || []
    formData.address = response.address || ''
    formData.weather = response.weather || ''

    // 处理图片数据
    if (response.photos && response.photos.length > 0) {
      formData.photos = response.photos

      // 创建文件列表，确保包含所有必要的字段
      const newFileList = response.photos.map((photo, index) => {
        // 使用后端返回的文件类型，如果没有则从URL推断
        let fileType = photo.fileType || 'image/jpeg' // 默认图片类型

        if (!photo.fileType) {
          // 尝试从URL推断文件类型
          const url = photo.url.toLowerCase()
          if (url.includes('.jpg') || url.includes('.jpeg')) {
            fileType = 'image/jpeg'
          } else if (url.includes('.png')) {
            fileType = 'image/png'
          } else if (url.includes('.gif')) {
            fileType = 'image/gif'
          } else if (url.includes('.webp')) {
            fileType = 'image/webp'
          } else if (url.includes('.bmp')) {
            fileType = 'image/bmp'
          } else if (url.includes('.mp4')) {
            fileType = 'video/mp4'
          } else if (url.includes('.avi')) {
            fileType = 'video/avi'
          } else if (url.includes('.mov')) {
            fileType = 'video/quicktime'
          } else if (url.includes('.wmv')) {
            fileType = 'video/x-ms-wmv'
          } else if (url.includes('.flv')) {
            fileType = 'video/x-flv'
          } else if (url.includes('.webm')) {
            fileType = 'video/webm'
          }
        }

        return {
          id: `existing-${index}`,
          name: `图片${index + 1}`,
          status: 'finished' as const,
          url: photo.url,
          fileType: fileType // 添加 fileType 字段到 UploadFileInfo
        }
      })

      // 使用 nextTick 确保 DOM 更新后再设置 fileList
      await nextTick()
      fileList.value = newFileList
    } else {
      formData.photos = []
      fileList.value = []
    }

    console.log('表单数据已填充:', formData)
    console.log('文件列表已更新:', fileList.value)
  } catch (error) {
    message.error('加载说说数据失败')
    console.error('加载说说数据失败:', error)
  }
}

// 加载标签
const loadTags = async () => {
  try {
    tagLoading.value = true
    const tags = await tagApi.getTagList(1) // 1代表说说标签
    console.log('获取到的标签列表:', tags)

    // 将标签数据转换为选项格式
    tagOptions.value = tags.map(tag => ({
      label: tag.tagName,  // 使用tagName字段
      value: tag.tagName   // 使用tagName字段
    }))

    // 初始化过滤后的选项
    filteredTagOptions.value = [...tagOptions.value]

    console.log('转换后的标签选项:', tagOptions.value)
  } catch (error) {
    message.error('加载标签失败')
    console.error('加载标签失败:', error)
  } finally {
    tagLoading.value = false
  }
}

// 处理标签搜索
const handleTagSearch = (keyword: string) => {
  console.log('搜索标签:', keyword)
  searchKeyword.value = keyword

  if (!keyword.trim()) {
    // 如果搜索关键词为空，显示所有标签
    filteredTagOptions.value = [...tagOptions.value]
    return
  }

  // 过滤匹配的标签
  const matchedTags = tagOptions.value.filter(tag =>
    tag.label.toLowerCase().includes(keyword.toLowerCase())
  )

  // 检查是否已存在该标签
  const tagExists = tagOptions.value.some(tag =>
    tag.label.toLowerCase() === keyword.toLowerCase()
  )

  // 如果不存在，添加创建选项
  if (!tagExists && keyword.trim()) {
    filteredTagOptions.value = [
      ...matchedTags,
      {
        label: `创建标签 "${keyword}"`,
        value: keyword,
        type: 'create'
      }
    ]
  } else {
    filteredTagOptions.value = matchedTags
  }
}

// 处理标签选择
const handleTagChange = async (value: string[]) => {
  console.log('标签选择变化:', value)

  // 检查是否有需要创建的标签
  const createPromises = value.map(async (v) => {
    // 检查是否是创建选项
    const createOption = filteredTagOptions.value.find(option =>
      option.value === v && option.type === 'create'
    )

    if (createOption) {
      // 创建新标签
      const tagName = createOption.value
      const result = await createTag(tagName)
      return result ? tagName : null
    }

    return v
  })

  // 等待所有创建操作完成
  const results = await Promise.all(createPromises)
  const validTags = results.filter(tag => tag !== null) as string[]

  formData.tags = validTags
}

// 创建新标签
const createTag = async (keyword: string) => {
  console.log('创建新标签:', keyword)
  tagLoading.value = true
  try {
    const newTag = await tagApi.addTag({
      tagName: keyword,  // 使用正确的字段名
      tagType: 1  // 1代表说说标签
    })
    console.log('创建标签成功:', newTag)
    message.success(`标签 "${keyword}" 已创建`)

    // 刷新标签列表
    await loadTags()

    return keyword
  } catch (error) {
    console.error('创建标签失败:', error)
    if (error instanceof Error) {
      message.error(error.message)
    } else {
      message.error('创建标签失败')
    }
    return null
  } finally {
    tagLoading.value = false
  }
}

// 移除标签
const removeTag = (tag: string) => {
  console.log('移除标签:', tag)
  formData.tags = formData.tags.filter(t => t !== tag)
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()

    submitting.value = true

    // 从 fileList 中提取图片数据
    const photos = fileList.value
      .filter(file => file.status === 'finished' && file.url)
      .map(file => ({
        url: file.url!
      }))

    const submitData: any = {
      content: formData.content,
      photos: photos,
      tags: formData.tags,
      address: formData.address,
      weather: formData.weather
    }

    console.log('准备提交的数据:', submitData)
    console.log('fileList.value:', fileList.value)
    console.log('提取的 photos:', photos)

    if (isEdit.value && talkId.value) {
      submitData.id = talkId.value
      await talkApi.updateTalk(submitData)
      message.success('更新成功！')
    } else {
      await talkApi.addTalk(submitData)
      message.success('发布成功！')
    }

    // 跳转回说说列表页
    router.push('/talk')
  } catch (error) {
    if (error instanceof Error) {
      message.error(error.message)
    } else {
      message.error('操作失败')
    }
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

// 取消操作
const handleCancel = () => {
  router.push('/talk')
}

// 重置表单
const handleReset = () => {
  formData.content = ''
  formData.photos = []
  formData.tags = []
  formData.address = ''
  formData.weather = ''
  fileList.value = []
  uploadedFiles.value = []
}

// 组件卸载前清理
onBeforeUnmount(() => {
  // 移除自动删除七牛云文件的逻辑，避免误删数据
})
</script>

<style scoped>
.talk-publish-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.publish-card {
  border-radius: 8px;
}

@media (max-width: 768px) {
  .talk-publish-page {
    padding: 10px;
  }
}
</style>
